<template>
  <div class="ppt-container" ref="containerRef">
    <div v-if="error" class="error-message">
      <h3>错误</h3>
      <p>{{ error }}</p>
      <button @click="initializeDocmee">重试</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { DocmeeUI, CreatorType } from '@docmee/sdk-ui'
import axios from 'axios'

const containerRef = ref<HTMLDivElement | null>(null)
const docmeeInstance = ref<DocmeeUI | null>(null)
const error = ref('')

import { createToken, refreshToken } from '@/api/ppt'

const initializeDocmee = async () => {
  error.value = ''
  
  try {
    // 确保容器元素存在
    await nextTick()
    
    if (!containerRef.value) {
      throw new Error('容器元素未找到')
    }

    // 使用API模块获取token
    let token = ''
    try {
      // 获取当前用户信息（实际项目中应从状态管理获取）
      const user = null as any
      
      const responseData = await createToken({
        uid: user?.id || null,
        limit: user ? 10 : 0,
        timeOfHours: 2
      })
      
      console.log('Token API完整响应:', responseData)
      
      // 检查响应对象是否有效
      if (!responseData) {
        throw new Error('API返回空响应')
      }
      
      // 检查响应数据结构 - 适配不同的响应格式
      if ((responseData as any).token) {
        // 直接有token字段的情况
        token = (responseData as any).token
      } else if ((responseData as any).code !== undefined && (responseData as any).data && (responseData as any).data.token) {
        // 标准API响应格式
        if ((responseData as any).code !== 0) {
          throw new Error(`API返回错误: ${(responseData as any).message || '未知错误'}`)
        }
        token = (responseData as any).data.token
      } else {
        console.error('无效的响应结构:', responseData)
        throw new Error('API返回格式错误')
      }
      
    } catch (err: any) {
      console.error('获取token时出错:', err)
      throw new Error('获取token失败: ' + (err.message || '未知错误'))
    }
    
    // 如果之前有实例，先销毁
    if (docmeeInstance.value) {
      docmeeInstance.value.destroy()
      docmeeInstance.value = null
    }

    // 初始化DocmeeUI
    docmeeInstance.value = new DocmeeUI({
      container: containerRef.value,
      page: 'creator-v2',
      token: token,
      mode: 'light',
      lang: 'zh',
      creatorData: {
        type: CreatorType.AI_GEN,
        subject: 'Ai行业未来10年的发展预测'
      },
      onMessage: async (message: any) => {
        console.log('监听事件', message)
        if (message.type === 'invalid-token') {
          try {
            // 使用当前token刷新
            const response = await refreshToken({ token: token })
            if (response.status !== 200 || !response.data.data?.token) {
              throw new Error('刷新token失败')
            }
            const newToken = response.data.data.token
            docmeeInstance.value?.updateToken(newToken)
            error.value = ''
          } catch (err) {
            error.value = 'token刷新失败，请重试'
          }
        } else if (message.type === 'beforeGenerate') {
          const { subtype, fields } = message.data || {}
          if (subtype === 'outline') {
            console.log('即将生成ppt大纲', fields)
            return true
          } else if (subtype === 'ppt') {
            console.log('即将生成ppt', fields)
            return true
          }
        } else if (message.type === 'error') {
          if (message.data?.code === 88) {
            error.value = '您的次数已用完'
          } else {
            error.value = '发生错误：' + (message.data?.message || '未知错误')
          }
        }
      }
    })
  } catch (err: any) {
    error.value = err.message || '初始化失败'
    console.error('初始化DocmeeUI失败:', err)
  }
}

onMounted(() => {
  initializeDocmee()
})

onUnmounted(() => {
  if (docmeeInstance.value) {
    docmeeInstance.value.destroy()
    docmeeInstance.value = null
  }
})
</script>

<style scoped>
.ppt-container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  border-radius: 12px;
  overflow: hidden;
  background: linear-gradient(-157deg, #f57bb0, #867dea);
  position: relative;
}

.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.error-message h3 {
  color: #f56c6c;
  margin-bottom: 10px;
}

.error-message button {
  margin-top: 15px;
  padding: 8px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.error-message button:hover {
  background-color: #66b1ff;
}
</style>
